package com.golxen.framework.common.server.game.cmd.user.login;


import com.golxen.framework.AgentProtocol;
import com.golxen.framework.GameProtocol;
import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.PBPacket.PBPacketUtils;
import com.golxen.framework.common.server.game.cmd.Cmd;
import com.golxen.framework.common.server.game.cmd.Command;
import com.golxen.framework.netty.session.game.GameServerLinkedSet;
import com.golxen.framework.user.dao.UserBussiness;
import com.golxen.framework.user.dao.entity.UserInfo;
import com.golxen.framework.user.player.GamePlayer;
import com.golxen.framework.user.player.GamePlayerMgr;
import com.golxen.protojava.LoginProto;
import com.golxen.utils.LogUtil;
import com.mysql.cj.util.StringUtils;
import io.netty.channel.ChannelHandlerContext;

@Cmd(code = GameProtocol.S_AGENT_CHECK_LOGIN, desc = "网关服请求是否允许用户登录")
public class AgentReqLoginCheckCmd implements Command {

    

    @Override
    public Tuple execute(ChannelHandlerContext ctx, PBPacket packet) throws Exception {
        LoginProto.LoginReqMsg reqMsg = LoginProto.LoginReqMsg.parseFrom(packet.toByteArray());
        long userId = reqMsg.getUserId();
        long nowTime = System.currentTimeMillis();

        UserInfo userInfo;
        GamePlayer player = GamePlayerMgr.getPlayer(packet.getPlayerId());
        if (player == null) {
            userInfo = UserBussiness.getUserInfoByUserId(packet.getPlayerId());
        } else {
            userInfo = player.getUserInfo();
        }

        if (userInfo == null) {
            return new Tuple(null, null);
        }


        LogUtil.COMMON.info("player login,userId:{},WorldMgr getPlayer use time:{}ms", packet.getPlayerId(),
                System.currentTimeMillis() - nowTime);
        boolean result = null != player;
        String clientVersion = reqMsg.getClientVer();
        if (!StringUtils.isNullOrEmpty(clientVersion)) {
            LogUtil.COMMON.info("player login,userId:{},clientVersion:{}", userId, clientVersion);
        } else {
            LogUtil.COMMON.info("player login,userId:{},clientVersion is empty", userId);
        }
        LoginProto.LoginResultMsg.Builder checkMsg = LoginProto.LoginResultMsg.newBuilder();
        checkMsg.setUserId(userId);
        checkMsg.setResult(result);
        PBPacket pkg = PBPacketUtils.buildMessage(AgentProtocol.A_LOGIN_RESPONSE, checkMsg);
        GameServerLinkedSet.send(userId, pkg);
        return new Tuple(null, null);
    }


}
